package com.cet.programmercarl.algorithmperformancanalysis.二叉树.二叉树的遍历;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;

/**
 * @program: algorithm
 * @description: 二叉树后序遍历
 * @author: 陈恩涛
 * @create: 2022-07-14 11:09
 **/
public class LC145 {

    public static void main(String[] args) {

    }

    public List<Integer> postorderTraversal(TreeNode root) {
        final List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        final Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            final TreeNode node = stack.pop();
            result.add(node.val);
            // 中右左遍历顺序
            if (node.left != null) {
                stack.push(node.left);
            }
            if (node.right != null) {
                stack.push(node.right);
            }
        }
        // 翻转后，左右中
        Collections.reverse(result);
        return result;
    }
}
